package com.ck.company.service.impl;

import com.ck.common.service.OperationLogService;
import com.ck.company.service.CpPictureGroupService;
import com.ck.company.service.CpPictureService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.ModuleConstant;
import com.ck.constant.PictureGroupConstant;
import com.ck.constant.RequestConstant;
import com.ck.dao.PictureGroupMapper;
import com.ck.exception.ServiceException;
import com.ck.model.common.OperationLog;
import com.ck.model.common.PictureGroup;
import com.ck.model.common.User;
import com.ck.model.company.dto.PictureGroupTreeDTO;
import com.ck.model.company.dto.ProgramPictureGroupTreeDTO;
import com.ck.util.HttpUtils;
import com.ck.util.TreeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片组Service实现类
 *
 * @author dxy
 * @date 2018/7/4 11:51
 */
@Service("cpPictureGroupService")
public class CpPictureGroupServiceImpl implements CpPictureGroupService {
    @Autowired
    private PictureGroupMapper pictureGroupMapper;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private CpPictureService cpPictureService;

    /**
     * 保存图片组
     *
     * @param pictureGroup PictureGroup
     * @param request      HttpServletRequest
     */
    @Override
    public void savePictureGroup(PictureGroup pictureGroup, HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        String companyCode = loginUser.getCompanyCode();
        pictureGroup.setCompanyCode(companyCode);
        pictureGroupMapper.insertPictureGroup(pictureGroup);
        //记录操作日志
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(companyCode);
        operationLog.setOperationContent("保存图片组,图片组ID为:" + pictureGroup.getPictureGroupId());
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_MATERIAL + "-" + ModuleConstant.MODULE_PICTURE);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 修改图片组
     *
     * @param pictureGroup PictureGroup
     * @param request      HttpServletRequest
     */
    @Override
    public void updatePictureGroup(PictureGroup pictureGroup, HttpServletRequest request) {
        pictureGroupMapper.updatePictureGroupById(pictureGroup);
        //记录操作日志
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(loginUser.getCompanyCode());
        operationLog.setOperationContent("修改图片组,图片组ID为:" + pictureGroup.getPictureGroupId());
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_MATERIAL + "-" + ModuleConstant.MODULE_PICTURE);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 删除图片组
     *
     * @param pictureGroupId 图片组ID
     * @param request        HttpServletRequest
     */
    @Override
    public void deletePictureGroupById(Long pictureGroupId, HttpServletRequest request) throws ServiceException {
        if (pictureGroupId == null) {
            throw new ServiceException("图片组ID不能为空");
        }
        //检测图片ID是否存在
        PictureGroup pictureGroup = pictureGroupMapper.getPictureGroupById(pictureGroupId);
        if (pictureGroup == null) {
            throw new ServiceException("图片组信息不存在");
        }
        //从ck_picture表中检测分组ID是否在使用，如果再使用，不允许删除
        Long count = cpPictureService.countPictureByPictureGroupId(pictureGroupId, pictureGroup.getCompanyCode());
        if (count != null && count > 0) {
            throw new ServiceException("该图片组被使用中，请删除关联关系");
        }
        //删除图片组
        pictureGroupMapper.deletePictureGroupById(pictureGroupId);
        //记录操作日志
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(loginUser.getCompanyCode());
        operationLog.setOperationContent("删除图片组,图片组ID为:" + pictureGroup.getPictureGroupId());
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_MATERIAL + "-" + ModuleConstant.MODULE_PICTURE);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 获取公司的分组树列表
     *
     * @param companyCode 商家编码
     * @return List<PictureGroupTreeDTO>
     */
    @Override
    public List<PictureGroupTreeDTO> listPictureGroupTree(String companyCode) throws ServiceException {
        if (StringUtils.isBlank(companyCode)) {
            throw new ServiceException("公司编码不能为空");
        }
        List<PictureGroupTreeDTO> pictureGroupTreeList = pictureGroupMapper.listPictureGroupTree(companyCode);
        //转为树形结构
        List result = new ArrayList<PictureGroupTreeDTO>();
        if (CollectionUtils.isNotEmpty(pictureGroupTreeList)) {
            PictureGroupTreeDTO treeDTO = new PictureGroupTreeDTO();
            treeDTO.setLabel("全部分组");
            treeDTO.setChildren(TreeUtils.getTreeList(pictureGroupTreeList));
            result.add(treeDTO);
        }
        return result;
    }

    /**
     * 通过名称查找图片组
     *
     * @param companyCode      商家编码
     * @param pictureGroupName 图片组名称
     * @return PictureGroup
     */
    @Override
    public PictureGroup getPictureGroupByName(String companyCode, String pictureGroupName) throws ServiceException {
        if (StringUtils.isBlank(companyCode) || StringUtils.isBlank(pictureGroupName)) {
            throw new ServiceException("输入参数不能为空");
        }
        return pictureGroupMapper.getPictureGroupByName(companyCode, pictureGroupName);
    }

    /**
     * 通过编码获取图片组
     *
     * @param companyCode      商家编码
     * @param pictureGroupCode 图片组编码
     * @return PictureGroup
     */
    @Override
    public PictureGroup getPictureGroupByCode(String companyCode, String pictureGroupCode) throws ServiceException {
        if (StringUtils.isBlank(companyCode) || StringUtils.isBlank(pictureGroupCode)) {
            throw new ServiceException("输入参数不能为空");
        }
        return pictureGroupMapper.getPictureGroupByCode(companyCode, pictureGroupCode);
    }

    /**
     * 获取公司的分组树列表(无层级关系)
     *
     * @param companyCode    商家编码
     * @param pictureGroupId 图片组ID
     * @return List<PictureGroupTreeDTO>
     */
    @Override
    public List<ProgramPictureGroupTreeDTO> listProgramPictureGroupTree(String companyCode, Long pictureGroupId)
            throws ServiceException {
        if (StringUtils.isBlank(companyCode)) {
            throw new ServiceException("公司编码不能为空");
        }
        //转为树形结构
        List<ProgramPictureGroupTreeDTO> pictureGroupTreeList = pictureGroupMapper.listProgramPictureGroupTreeForClient(companyCode);
        if (CollectionUtils.isNotEmpty(pictureGroupTreeList)) {
            for (ProgramPictureGroupTreeDTO groupTreeDTO : pictureGroupTreeList) {
                if (null != groupTreeDTO.getPictureGroupId() && groupTreeDTO.getPictureGroupId().equals(pictureGroupId)) {
                    groupTreeDTO.setChecked(true);
                } else {
                    groupTreeDTO.setChecked(false);
                }
                groupTreeDTO.setOpen(true);
            }
        } else {
            pictureGroupTreeList = new ArrayList<>();
        }
        long totalPictureNumWithGroup = cpPictureService.countPictureByCompany(companyCode, true);
        //默认添加一个全部分组
        ProgramPictureGroupTreeDTO allGroupDTO = new ProgramPictureGroupTreeDTO();
        if (null == pictureGroupId) {
            allGroupDTO.setChecked(true);
        } else if (PictureGroupConstant.ALL_DEVICE_GROUP_ID.equals(pictureGroupId)) {
            allGroupDTO.setChecked(true);
        } else {
            allGroupDTO.setChecked(false);
        }
        allGroupDTO.setPictureNum(totalPictureNumWithGroup);
        allGroupDTO.setOpen(true);
        allGroupDTO.setLabel(PictureGroupConstant.ALL_PICTURE_GROUP_NAME);
        allGroupDTO.setPictureGroupId(PictureGroupConstant.ALL_DEVICE_GROUP_ID);
        allGroupDTO.setPicureGroupCode(PictureGroupConstant.ALL_PICTURE_GROUP_CODE);
        pictureGroupTreeList.add(0, allGroupDTO);

        //默认添加一个未分组
        long totalPictureNumNoGroup = cpPictureService.countPictureByCompany(companyCode, false);
        ProgramPictureGroupTreeDTO noGroupDTO = new ProgramPictureGroupTreeDTO();
        noGroupDTO.setOpen(false);
        if (null != pictureGroupId && PictureGroupConstant.NO_DEVICE_GROUP_ID.equals(pictureGroupId)) {
            noGroupDTO.setChecked(true);
        } else {
            noGroupDTO.setChecked(false);
        }
        noGroupDTO.setPictureNum(totalPictureNumNoGroup);
        noGroupDTO.setLabel(PictureGroupConstant.NO_PICTURE_GROUP_NAME);
        noGroupDTO.setPictureGroupId(PictureGroupConstant.NO_DEVICE_GROUP_ID);
        noGroupDTO.setPicureGroupCode(PictureGroupConstant.NO_PICTURE_GROUP_CODE);
        pictureGroupTreeList.add(pictureGroupTreeList.size(), noGroupDTO);
        return pictureGroupTreeList;
    }


    /**
     * 获取公司的分组树列表
     *
     * @param companyCode    商家编码
     * @param pictureGroupId 图片组ID
     * @return List<PictureGroupTreeDTO>
     */
    @Override
    public List<ProgramPictureGroupTreeDTO> treePictureGroupForProgram(String companyCode, Long pictureGroupId)
            throws ServiceException {
        if (StringUtils.isBlank(companyCode)) {
            throw new ServiceException("公司编码不能为空");
        }
        //转为树形结构
        List<ProgramPictureGroupTreeDTO> data = new ArrayList<>();
        List<ProgramPictureGroupTreeDTO> pictureGroupTreeList = pictureGroupMapper.listProgramPictureGroupTreeForClient(companyCode);
        if (CollectionUtils.isNotEmpty(pictureGroupTreeList)) {
            for (ProgramPictureGroupTreeDTO groupTreeDTO : pictureGroupTreeList) {
                if (null != groupTreeDTO.getPictureGroupId() && groupTreeDTO.getPictureGroupId().equals(pictureGroupId)) {
                    groupTreeDTO.setChecked(true);
                } else {
                    groupTreeDTO.setChecked(false);
                }
                groupTreeDTO.setOpen(true);
            }
            pictureGroupTreeList = TreeUtils.getTreeList(pictureGroupTreeList);
        } else {
            pictureGroupTreeList = new ArrayList<>();
        }
        long totalPictureNumWithGroup = cpPictureService.countPictureByCompany(companyCode, true);
        //默认添加一个全部分组
        ProgramPictureGroupTreeDTO allGroupDTO = new ProgramPictureGroupTreeDTO();
        if (null == pictureGroupId) {
            allGroupDTO.setChecked(true);
        } else if (PictureGroupConstant.ALL_DEVICE_GROUP_ID.equals(pictureGroupId)) {
            allGroupDTO.setChecked(true);
        } else {
            allGroupDTO.setChecked(false);
        }
        allGroupDTO.setPictureNum(totalPictureNumWithGroup);
        allGroupDTO.setOpen(true);
        allGroupDTO.setChildren(pictureGroupTreeList);
        allGroupDTO.setLabel(PictureGroupConstant.ALL_PICTURE_GROUP_NAME);
        allGroupDTO.setPictureGroupId(PictureGroupConstant.ALL_DEVICE_GROUP_ID);
        allGroupDTO.setPicureGroupCode(PictureGroupConstant.ALL_PICTURE_GROUP_CODE);
        data.add(allGroupDTO);

        //默认添加一个未分组
        long totalPictureNumNoGroup = cpPictureService.countPictureByCompany(companyCode, false);
        ProgramPictureGroupTreeDTO noGroupDTO = new ProgramPictureGroupTreeDTO();
        noGroupDTO.setOpen(false);
        if (null != pictureGroupId && PictureGroupConstant.NO_DEVICE_GROUP_ID.equals(pictureGroupId)) {
            noGroupDTO.setChecked(true);
        } else {
            noGroupDTO.setChecked(false);
        }
        noGroupDTO.setPictureNum(totalPictureNumNoGroup);
        noGroupDTO.setLabel(PictureGroupConstant.NO_PICTURE_GROUP_NAME);
        noGroupDTO.setPictureGroupId(PictureGroupConstant.NO_DEVICE_GROUP_ID);
        noGroupDTO.setPicureGroupCode(PictureGroupConstant.NO_PICTURE_GROUP_CODE);
        data.add(noGroupDTO);
        return data;
    }

    @Override
    public ProgramPictureGroupTreeDTO getPictureGroupTreeById(String companyCode, Long pictureGroupId) throws ServiceException {
        return pictureGroupMapper.getPictureGroupTreeById(companyCode, pictureGroupId);
    }
}
